﻿using System;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using Eneta.Portal.Common;
using Microsoft.SharePoint;

namespace Eneta.Portal.Companies.Controls
{
    public class RandomCompanyControl : UserControl
    {
        protected HtmlAnchor companyTitleLink;
        protected HtmlImage companyLogo;
        protected HtmlAnchor companyLogoLink;
        protected HtmlGenericControl companyDescription;

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            try
            {


                var siteId = SPContext.Current.Site.ID;

                var sec = new SPSecurity.CodeToRunElevated(delegate
                       {
                           using (var site = new SPSite(siteId))
                           using (var web = site.OpenWeb("/firmad/"))
                           {
                               var list = web.Lists["Lehed"];

                               var queryString =
                                   "<Where><And><Eq><FieldRef Name='ContentType' /><Value Type='Text'>Firma</Value></Eq>" +
                                   "<Eq><FieldRef Name='_ModerationStatus' /><Value Type='ModStat'>Kinnitatud</Value></Eq></And></Where>";
                               var query = new SPQuery {Query = queryString};
                               var items = list.GetItems(query);

                               if (items == null)
                                   return;
                               if (items.Count == 0)
                               {
                                   Logger.LogInfo(
                                       "OnLoad(): Found 0 companies",
                                       GetType().ToString());
                                   return;
                               }
                               var random = new Random(DateTime.Now.Millisecond);
                               var index = random.Next(0, items.Count - 1);
                               var item = items[index];

                               if (item["Comments"] != null)
                                   companyDescription.InnerText = item["Comments"].ToString();
                               else if(item["PublishingPageContent"]!= null)
                               {
                                   companyDescription.InnerText = item["PublishingPageContent"].ToString();
                                   if (!string.IsNullOrEmpty(companyDescription.InnerText))
                                   {
                                       if (companyDescription.InnerText.Length > 255)
                                           companyDescription.InnerText = companyDescription.InnerText.Substring(0, 255) + "...";
                                   }
                                   else
                                       companyDescription.InnerHtml = "&nbsp;";
                               }
                               else
                                   companyDescription.InnerHtml = "&nbsp;";
                               companyTitleLink.InnerText = item.Title;
                               companyTitleLink.HRef = "/firmad/Lehed/" + item["LinkFilename"];

                               companyLogoLink.HRef = companyTitleLink.HRef;

                               companyLogo.Visible = false;
                               var fileName = item["FileLeafRef"].ToString().Replace(".aspx","_small.png");
                               var logoUrl = "/SiteCollectionImages/firmad/" + fileName;
                               var logoFile = web.Site.RootWeb.GetFile(logoUrl);

                               if (logoFile != null)
                                   if (logoFile.Exists)
                                   {
                                       companyLogo.Src = logoUrl;
                                       companyLogo.Visible = true;
                                   }
                               companyLogoLink.Visible = companyLogo.Visible;
                           }
                       });
                SPSecurity.RunWithElevatedPrivileges(sec);
            }
            catch(Exception ex)
            {
                Logger.LogWarning("Onload(): Exception occured", GetType().ToString());
                Logger.LogException(ex);
            }
        }
    }
}
